﻿/**************************************************************
* 功   能 ：安装类 程序安装后添加注册表信息
* 创 建 人：ColaShou
* 创建时间：2023-08-04
* 最近修改人：
* 修改  时间：
* 修改  内容:
* ***************************************************************/
namespace ColaWinFormFrameWork
{
    using System;
    using System.ComponentModel;
    using System.Configuration.Install;
    using System.IO;
    using ColaWinFormFrameWork.UICommon;
    using Microsoft.Win32;

    /// <summary>
    /// InstallerRegister.
    /// </summary>
    [RunInstaller(true)]
    public partial class InstallerRegister : System.Configuration.Install.Installer
    {
        /// <summary>
        /// InstallerRegister.
        /// </summary>
        public InstallerRegister()
        {
            this.InitializeComponent();
            this.AfterInstall += new InstallEventHandler(this.Installer_AfterInstall);
            this.AfterUninstall += new InstallEventHandler(this.Installer_AfterUninstall);
        }

        /// <summary>
        /// 安装路径.
        /// </summary>
        private string installFilePath = string.Empty;

        /// <summary>
        /// 安装完成后触发写入注册表事件.
        /// </summary>
        /// <param name="sender">sender.</param>
        /// <param name="e">e.</param>
        private void Installer_AfterInstall(object sender, InstallEventArgs e)
        {
            this.AddLog("----注册表开始写入---");
            // this.AddLog("安装地址:" + this.installFilePath);
            string path = this.Context.Parameters["targetdir"];
            this.AddLog("注册表路径:" + path);
            this.installFilePath = path.Substring(1, path.Length - 2);
            this.AddLog("程序安装路径:" + this.installFilePath);
            this.AddLog("安装程序文件路径:" + Path.Combine(this.installFilePath, UIConst.ProgramExeName)); // UIConst.ProgramExeName 程序名称
            var result = this.RegeditCreate(UIConst.RegisterName, Path.Combine(this.installFilePath, UIConst.ProgramExeName), string.Empty);
            this.AddLog("注册表修改结果:" + result);
        }

        /// <summary>
        /// 卸载完成之后触发删除注册表事件.
        /// </summary>
        /// <param name="sender">sender.</param>
        /// <param name="e">e.</param>
        private void Installer_AfterUninstall(object sender, InstallEventArgs e)
        {
            this.AddLog("注册表信息删除开始:");
            var result = this.RegeditDelete(UIConst.RegisterName); // 根据注册名称去删除
            this.AddLog("注册表信息删除:" + result);
        }

        /// <summary>
        /// 注册协议.
        /// </summary>
        /// <param name="rootKey">根节点.</param>
        /// <param name="fileApplicationPath">应用程序路径.</param>
        /// <param name="fileApplicationIco">应用程序打开图标,可选值.</param>
        /// <returns>bool.</returns>
        private bool RegeditCreate(string rootKey, string fileApplicationPath, string fileApplicationIco)
        {
            // 获取注册表HKEY_CLASSES_ROOT
            RegistryKey regClassRoot = Registry.ClassesRoot;
            this.AddLog(regClassRoot.Name);

            try
            {
                RegistryKey reg_key = regClassRoot.OpenSubKey(rootKey, true);
                if (reg_key == null)
                {
                    // 创建子节点HKEY_CLASSES_ROOT\tpswftest
                    RegistryKey reg_sjbs = regClassRoot.CreateSubKey(rootKey);

                    // 添加默认项
                    reg_sjbs.SetValue("", "URL: " + rootKey + " Protocol Handler");

                    // 协议别名
                    reg_sjbs.SetValue("URL Protocol", fileApplicationPath);

                    // 创建[HKEY_CLASSES_ROOT\colawinformframework\DefaultIcon]
                    RegistryKey reg_DefaultIcon = reg_sjbs.CreateSubKey("DefaultIcon");
                    if (!string.IsNullOrEmpty(fileApplicationPath))
                    {
                        // 设置自定义图标
                        reg_DefaultIcon.SetValue(string.Empty, fileApplicationIco);
                    }
                    else
                    {
                        // 设置系统定义图标
                        reg_DefaultIcon.SetValue(string.Empty, fileApplicationPath + ",1");
                    }

                    // 创建呼出处理程序[HKEY_CLASSES_ROOT\colawinformframework\shell\open\command]
                    RegistryKey reg_command = reg_sjbs.CreateSubKey("shell").CreateSubKey("open").CreateSubKey("command");

                    // %1 表示传递的参数，再次%1表示调用处显示链接文本
                    reg_command.SetValue(string.Empty, "\"" + fileApplicationPath + "\" \"%1\"");
                }

                return true;
            }
            catch (Exception ex)
            {
                this.AddLog(ex.Message.ToString());
                return false;
            }
            finally
            {
                regClassRoot.Close();
            }
        }

        /// <summary>
        /// 删除协议.
        /// </summary>
        /// <param name="rootKey">根节点.</param>
        /// <returns>RegeditDelete.</returns>
        private bool RegeditDelete(string rootKey)
        {
            // 获取注册表HKEY_CLASSES_ROOT
            RegistryKey regClassRoot = Registry.ClassesRoot;
            try
            {
                // 获取注册表[HKEY_CLASSES_ROOT\targetdir]项
                RegistryKey reg_sjbs = regClassRoot.OpenSubKey(rootKey, true);
                if (reg_sjbs != null)
                {
                    regClassRoot.DeleteSubKeyTree(rootKey);
                    return true;
                }
                else
                {
                    this.AddLog("注册表中【" + regClassRoot + "\\" + rootKey + "】不存在！");
                    return false;
                }
            }
            catch (Exception ex)
            {
                // 添加错误日志
                this.AddLog(ex.Message.ToString());
                return false;
            }
            finally
            {
                regClassRoot.Close();
            }
        }

        /// <summary>
        /// 安装日志.
        /// </summary>
        /// <param name="message">message.</param>
        private void AddLog(string message)
        {
            string rootPath = UIConst.InstallLogPath; // 安装日志
            try
            {
                var logPath = Path.Combine(rootPath, "Log");
                if (!Directory.Exists(logPath))
                {
                    Directory.CreateDirectory(logPath);
                }

                var filePath = Path.Combine(logPath, "Install.LOG");
                if (File.Exists(filePath))
                {
                    var file = new FileInfo(filePath);
                    if (file.Length > 102400)
                    {
                        file.MoveTo(Path.Combine(
                            logPath,
                            "Install." + DateTime.Now.ToString("yyyyMMddHHmmssf") + ".LOG"));
                    }
                }

                using (FileStream fileStream = File.Open(filePath, FileMode.Append, FileAccess.Write))
                {
                    using (StreamWriter writer = new StreamWriter(fileStream))
                    {
                        writer.WriteLine(DateTime.Now.ToString());
                        writer.WriteLine(message);
                        writer.Close();
                    }

                    fileStream.Close();
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
    }
}
